package main

import (
	"fmt"
	"net/http"
	"time"

	"gitee.com/zhangycsz/glin"
	"gitee.com/zhangycsz/glin/middleware"
	"gitee.com/zhangycsz/glin/util"
)

func main() {
	g := glin.New()
	g.Use(middleware.Logger())

	g.Use(func(next glin.HandlerFunc) glin.HandlerFunc {
		return func(c glin.Context) error {
			return next(c)
		}
	})
	g.GET("/index", func(c glin.Context) error {
		outStr := "/index/index 输出："

		return c.String(200, outStr)
	})

	g.GET("/login", func(c glin.Context) error {
		err := c.SetAuth("zhangyc", []byte("当前时间:"+time.Now().Format("2006-01-02 15:04:05")))
		if err != nil {
			fmt.Println("setsession err=", err)
		} else {
			fmt.Println("setsession ok")
		}
		return c.String(200, "/index/login")
	})
	//g.Use(checkAuth)
	admin := g.Group("/admin", checkAuth)

	admin.GET("/index", func(c glin.Context) error {
		data, err := c.GetAuth("zhangyc")
		if err != nil {
			fmt.Println("登录失败")
		}
		return c.String(200, "登录成功:"+string(data))
	})

	admin.GET("/user", func(c glin.Context) error {
		data, err := c.GetAuth("zhangyc")
		if err != nil {
			fmt.Println("登录失败")
		}
		return c.String(200, "登录成功:"+string(data))
	})

	certFile, keyFile, _ := util.GetTlsFile()
	err := g.StartTLS("0.0.0.0:8086", certFile, keyFile)
	if err != nil {
		fmt.Println("err=", err)
	} else {
		fmt.Println("ok")
	}
}

// 需要先login才能访问
func checkAuth(next glin.HandlerFunc) glin.HandlerFunc {
	return func(c glin.Context) error {
		data, err := c.GetAuth("zhangyc")
		if err != nil {
			fmt.Println("没有登录:", err)
		} else {
			fmt.Println("登录成功:", string(data))
		}
		fmt.Println("checkAuth--------path=", c.Path())
		err = c.CheckAuth("zhangyc")
		if err != nil {
			fmt.Println("没有登录", err)
			return c.Redirect(http.StatusFound, "/login")
		}
		return next(c)
	}
}
